var express = require('express')
const moment = require('moment')
var router = express.Router()
const sqlQuery = require('../../module/sqlQuery')
const { resJsonObject, recordsStatusArr } = require('../../module/canshu')

/* GET users listing. */
router.get('/', function (req, res, next) {
  const options = { categoryList: recordsStatusArr }
  res.render('admin/registrationRecords/recordsList', options)
})

router.get('/data', async function (req, res, next) {
  try {
    // keywords 搜索关键词 为空的时候 查询全部
    let {
      page,
      limit,
      keywords_patient_name = '',
      keywords_status = '',
    } = req.query
    console.log(req.query)

    page = parseInt(page ? page : 1)
    limit = parseInt(limit)
    const results = await sqlQuery(
      `SELECT re.id as id,
      patientslist.name as patient_name,
      doctors_category.name as clinic_name,
      re.registration_time as registration_time,
      re.visit_time as visit_time,
      doctorslist.name as doctor_name,
      re.status as record_status,
      re.content as record_content
      FROM registration_record as re
      LEFT JOIN patientslist
      ON re.patient_id=patientslist.id
      LEFT JOIN doctors_category
      ON re.clinic_id=doctors_category.id
      LEFT JOIN doctorslist
      ON re.doctor_id=doctorslist.id
      where patientslist.name like ? 
      and re.status like ?
      limit ?,?`,
      [
        '%' + keywords_patient_name + '%',
        '%' + keywords_status + '%',
        (page - 1) * 5,
        limit,
      ]
    )

    results.forEach((item, index, arr) => {
      // 日期变换
      arr[index] = {
        ...item,
        registration_time_text: moment(parseInt(item.registration_time)).format(
          'YYYY-MM-DD hh:mm:ss'
        ),
        visit_time_text: moment(parseInt(item.visit_time)).format(
          'YYYY-MM-DD hh:mm:ss'
        ),
      }
    })

    results.forEach((item, index, arr) => {
      // // 挂号状态变换
      recordsStatusArr.forEach((status_item) => {
        if (status_item.id === item.record_status) {
          arr[index] = {
            ...item,
            record_status_text: status_item.value,
          }
          return
        }
      })
    })

    // console.log(results)

    // 符合条件的总条数
    const [{ count_num }] = await sqlQuery(
      `select count(*) as count_num 
      FROM registration_record as re
      LEFT JOIN patientslist
      ON re.patient_id=patientslist.id
      LEFT JOIN doctors_category
      ON re.clinic_id=doctors_category.id
      LEFT JOIN doctorslist
      ON re.doctor_id=doctorslist.id
      where patientslist.name like ? 
      and re.status like ?`,
      ['%' + keywords_patient_name + '%', '%' + keywords_status + '%']
    )

    res.json(
      resJsonObject({
        code: 0,
        msg: '完成',
        data: {
          arr: Array.from(results),
          count: count_num,
        },
      })
    )
    // res.render('admin/users/userlist',{userlist:results});
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '获取失败',
        data: {
          error,
        },
      })
    )
  }
})

// 信息界面 编辑
router.get('/edit/:id', async function (req, res, next) {
  let sqlStr = `SELECT re.id as id,
  patientslist.name as patient_name,
  doctors_category.name as clinic_name,
  re.registration_time as registration_time,
  re.visit_time as visit_time,
  doctorslist.name as doctor_name,
  re.status as record_status,
  re.content as record_content
  FROM registration_record as re
  LEFT JOIN patientslist
  ON re.patient_id=patientslist.id
  LEFT JOIN doctors_category
  ON re.clinic_id=doctors_category.id
  LEFT JOIN doctorslist
  ON re.doctor_id=doctorslist.id
  where re.id = ?`

  // 获取分类列表
  const categoryList = recordsStatusArr

  // 获取角色列表
  const results = await sqlQuery(sqlStr, [req.params.id])
  // res.json(results)

  const recordInfo = {
    ...results[0],
    registration_time_text: moment(
      parseInt(results[0].registration_time)
    ).format('YYYY-MM-DD hh:mm:ss'),
    visit_time_text: moment(parseInt(results[0].visit_time)).format(
      'YYYY-MM-DD hh:mm:ss'
    ),
  }

  const options = { recordInfo, categoryList }
  res.render('admin/registrationRecords/editRecord.ejs', options)
})

router.post('/edit', async function (req, res, next) {
  try {
    let { record_id, category_id, content } = req.body

    // 1，更新角色表，
    await sqlQuery(
      'update registration_record set status =?,  content =? where id=?',
      [parseInt(category_id), content, parseInt(record_id)]
    )

    // 2，更新角色权限关联表

    // // 先删除原有的该角色的权限信息
    // await sqlQuery('delete from role_auth where roleid=?', [roleid])

    // // 添加新的角色权限信息
    // authlist.forEach(async (item) => {
    //   await sqlQuery(`insert into role_auth (roleid,authid)
    //   values (${parseInt(roleid)},${parseInt(item.value)}); `)
    // })

    res.json(
      resJsonObject({
        code: 0,
        msg: '更新成功',
      })
    )
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '更新失败',
        data: {
          error,
        },
      })
    )
  }
})

module.exports = router
